/*
 * @description:
 * @Author: lal
 * @Date: 2020-05-28 09:08:54
 * @LastEditors: lal
 * @LastEditTime: 2020-08-17 15:31:18
 */

const { ipcMain, app, Menu, Tray } = require("electron");
import { windows } from "../../windows/create-window";
import log from "electron-log";

let appIcon = null;

function createTray() {
  const iconName = "windows-icon.png";
  const iconName2 = "empty.ico";
  // eslint-disable-next-line no-undef
  let iconPath = `${__static}/${iconName}`;
  let iconPath2 = `${__static}/${iconName2}`;
  // log.info(process.platform);
  // const iconPath = path.join(__dirname, iconName);
  appIcon = new Tray(iconPath);

  const contextMenu = Menu.buildFromTemplate([
    {
      label: "退出",
      click: () => {
        windows["mainWindow"] = null;
        delete windows["mainWindow"];
        log.info("退出");
        // app.quit();
        app.exit();
        appIcon.destroy();
      },
    },
  ]);

  appIcon.setToolTip("Electron Demo in the tray.");
  appIcon.setContextMenu(contextMenu);
  let count = 0;
  let timer;

  appIcon.on("double-click", () => {
    if (!windows["mainWindow"].isVisible()) {
      windows["mainWindow"].show();
      windows["mainWindow"].setSkipTaskbar(false);
    }
    clearInterval(timer);
    appIcon.setImage(iconPath);
  });
  // appIcon.on("mouse-move", function(e, position) {
  //   log.info(position);
  // });

  ipcMain.handle("message", () => {
    timer = setInterval(function() {
      if (count++ % 2 == 0) {
        appIcon.setImage(iconPath);
      } else {
        appIcon.setImage(iconPath2);
      }
    }, 400);
  });
}
// ipcMain.on("put-in-tray", event => {});

ipcMain.on("remove-tray", () => {
  appIcon.destroy();
});

app.on("window-all-closed", () => {
  if (appIcon) appIcon.destroy();
});

export default createTray;
